//
// ResourceManager.cpp
// Usage: Kernel core component, manage all resource
// Create Date: 2009-03-05
// Author: MaJiuyue
//
#include <NewLife.h>
#include <string.h>
#include <errno.h>
#include "ResourceManager.h"

CResourceManager ResourceManager;

CResourceManager::CResourceManager()
	:m_ResourceNameMap(&ResourceNameMap::stringEqPredicate, 
			   &ResourceNameMap::stringHashFunction)
{
	iNextID = 1;
	// Treat self as a resource
	Resource *res = new Resource(this);
	ResourceManager.CreateResource(res, "core.ResourceManager");
}

CResourceManager::~CResourceManager()
{
}

int CResourceManager::CreateResource(
	Resource * pResource, 
	const char *strResourceName
)
{
	// If already exist a resource named strResourceName, then return EEXIST
	if(m_ResourceNameMap.lookup(strResourceName) != NULL)
		return -EEXIST;

	pResource->SetResourceID(iNextID);
	m_Resources.add(iNextID, pResource);
	if (strResourceName)
		m_ResourceNameMap.add(strResourceName, pResource);
	return iNextID++;
}

Resource * CResourceManager::RequestResource(int iResourceID)
{
	return m_Resources.lookup(iResourceID);
}

Resource * CResourceManager::RequestResource(const char *strResourceName)
{
	Resource * res = m_ResourceNameMap.lookup((char*)strResourceName);
	if(res==NULL)
		panic("Resource \"%s\" not exist!", strResourceName);

	return res;
}

void CResourceManager::DestoryResource(int iResourceID)
{
	Resource *res = m_Resources.remove(iResourceID);
	
	if (!res)
		return;

	for (unsigned int i=0; i<m_ResourceNameMap.length(); i++)
	{
		if(m_ResourceNameMap.getByIndex(i) == res)
		{
			m_ResourceNameMap.remove(m_ResourceNameMap.getKeyByIndex(i));
			break;
		}
	}
}

